import styles from './index.module.scss';
import Icon from '@/components/Icon';
import NavBar from '@/components/NavBar';
import Skeleton from '@/components/Skeleton';
import { useAppDispatch, useAppSelector } from '@/store';
import { clearArticleDetailAction, followUserAction, getArticleDetailAction } from '@/store/action/article';
import dayjs from 'dayjs';
import DOMPurify from 'dompurify';
import { useEffect, useRef, useState } from 'react';
import { useParams } from 'react-router-dom';
import hljs from 'highlight.js';
//GitHub主题风格
import 'highlight.js/styles/github.css';
import classnames from 'classnames';
import NoComment from './components/NoComment';
import CommentItem from './components/CommentItem';
import { clearCommentDataAction, getCommentByIdAction } from '@/store/action/comment';
import { map } from 'lodash';
import { commentItem } from '@/store/reducer/comment';
import { InfiniteScroll, Popup } from 'antd-mobile';
import CommentFooter from './components/CommentFooter';
import CommentReply from './components/CommentReply';
export default function Article() {
  const [visible, setVisible] = useState(false);
  const warpRef = useRef<HTMLDivElement>(null);
  const authRef = useRef<HTMLDivElement>(null);
  const commentRef = useRef<HTMLDivElement>(null);
  const showCommentStatus = useRef(false);

  const dispatch = useAppDispatch();
  const { id } = useParams<{ id: string }>();
  const { articleDetail } = useAppSelector((state) => state.article);
  const { commentData, replyOriginData } = useAppSelector((state) => state.comment);
  const { results, last_id, end_id } = commentData;
  // 上拉加载更多
  const loadMore = async () => {
    // 加载更多评论列表
    await dispatch(getCommentByIdAction(id, 'a', last_id));
  };
  // 关注作者
  const handleFollowed = async () => {
    const hasFollowed = articleDetail.is_followed;
    await dispatch(followUserAction(articleDetail.aut_id, hasFollowed));
    dispatch(getArticleDetailAction(id));
  };
  //跳转到评论区位置
  const jumpShowComment = () => {
    if (showCommentStatus.current) {
      warpRef.current?.scrollTo({ top: 0, behavior: 'smooth' });
    } else {
      // 滚动到评论区
      warpRef.current?.scrollTo({ top: commentRef.current!.offsetTop - 46, behavior: 'smooth' });
    }
    showCommentStatus.current = !showCommentStatus.current;
  };
  // 获取文章详情
  useEffect(() => {
    dispatch(getArticleDetailAction(id));
    // 获取评论列表
    dispatch(getCommentByIdAction(id, 'a'));
    return () => {
      // 清空文章详情
      dispatch(clearArticleDetailAction());
      // 清空评论列表
      dispatch(clearCommentDataAction());
    };
  }, [dispatch, id]);
  // 高亮代码
  useEffect(() => {
    if (!articleDetail.art_id) return;
    // 配置 highlight.js
    hljs.configure({
      // 忽略未经转义的 HTML 字符
      ignoreUnescapedHTML: true,
    });
    // 获取到渲染正文的容器元素
    // 查找容器元素下符合 pre code 选择器规则的子元素，进行高亮
    const codes = document.querySelectorAll('.dg-html pre code');
    if (codes.length > 0) {
      return codes.forEach((el) => hljs.highlightElement(el as HTMLElement));
    }
    // 查找容器元素下的 pre 元素，进行高亮
    const pre = document.querySelectorAll('.dg-html pre');
    if (pre.length > 0) {
      return pre.forEach((el) => hljs.highlightElement(el as HTMLElement));
    }
  }, [articleDetail.art_id]);
  // 监听滚动事件
  useEffect(() => {
    if (!articleDetail.art_id) return;
    const handleScroll = () => {
      if (!warpRef.current) return;
      const { top } = authRef.current!.getBoundingClientRect();
      if (top > 10) {
        setVisible(false);
      } else {
        setVisible(true);
      }
    };
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, [articleDetail.art_id]);

  return (
    <div className={styles.root}>
      <div className="root-wrapper">
        {/* 顶部导航栏 */}
        <NavBar right={<Icon type="icongengduo" />}>
          {visible && (
            <div className="nav-author">
              <img src={articleDetail.aut_photo} alt="" />
              <span className="name">{articleDetail.aut_name}</span>
              <span
                onClick={handleFollowed}
                className={classnames('follow', articleDetail.is_followed ? 'followed' : '')}
              >
                {articleDetail.is_followed ? '已关注' : '关注'}
              </span>
            </div>
          )}
        </NavBar>
        {/* 判断是否存在art_id */}
        {articleDetail.art_id ? (
          <div className="wrapper" ref={warpRef}>
            <div className="article-wrapper">
              {/* 文章描述信息栏 */}
              <div className="header">
                <h1 className="title">{articleDetail.title}</h1>

                <div className="info">
                  <span>{dayjs(articleDetail.pubdate).format('YYYY-MM-DD')}</span>
                  <span>{articleDetail.read_count} 阅读</span>
                  <span>{articleDetail.comm_count} 评论</span>
                </div>

                <div className="author" ref={authRef}>
                  <img src={articleDetail.aut_photo} alt="" />
                  <span className="name">{articleDetail.aut_name}</span>
                  <span onClick={handleFollowed} className={articleDetail.is_followed ? 'followed' : 'follow'}>
                    {articleDetail.is_followed ? '已关注' : '关注'}
                  </span>
                </div>
              </div>

              {/* 文章正文内容区域 */}
              <div className="content">
                <div
                  className="content-html dg-html"
                  dangerouslySetInnerHTML={{
                    __html: DOMPurify.sanitize(articleDetail.content),
                  }}
                ></div>
                <div className="date">发布文章时间：{dayjs().from(dayjs(articleDetail.pubdate))}</div>
                <div className="divider"></div>
                <div className="comment" ref={commentRef}>
                  {/* 评论总览信息 */}
                  <div className="comment-header">
                    <span>全部评论（{articleDetail.comm_count}）</span>
                    <span>{articleDetail.like_count} 点赞</span>
                  </div>
                  {/* 评论列表 */}
                  {articleDetail.comm_count === 0 ? (
                    <NoComment />
                  ) : (
                    <div className="comment-list">
                      {map(results, (item: commentItem) => {
                        return <CommentItem key={item.com_id} comment={item} />;
                      })}
                      <InfiniteScroll loadMore={loadMore} hasMore={last_id !== end_id}></InfiniteScroll>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        ) : (
          <Skeleton></Skeleton>
        )}
        {/* 底部 */}
        <CommentFooter detail={articleDetail} jumpToComment={jumpShowComment} />
        {/* 回复弹窗 */}
        <Popup destroyOnClose visible={!!replyOriginData.com_id} position="right">
          <CommentReply />
        </Popup>
      </div>
    </div>
  );
}
